
import { Component, OnInit, Injector, Input, ViewChild, AfterViewInit } from '@angular/core';
import { ModalComponentBase } from '@shared/component-base/modal-component-base';
import {
  CreateOrUpdateStockInput,
  SelectListItem,
  StockEditDto,
  StockServiceProxy
} from '@shared/service-proxies/service-proxies';
import { Validators, AbstractControl, FormControl } from '@angular/forms';
import { finalize } from 'rxjs/operators';
import * as XLSX from 'xlsx';
import { isNumber } from 'util';

@Component({
  selector: 'create-or-edit-stock',
  templateUrl: './import-subject.component.html',
  styleUrls: [
    'import-subject.component.less'
  ],
})

export class ImportSubjectComponent
  extends ModalComponentBase
  implements OnInit {
  isSubmit=false;
  inputdata = [];
  /**
  * 编辑时DTO的id
  */
  id: any;

  entity: StockEditDto = new StockEditDto();

  categoryList: Array<SelectListItem>;

  typeList: Array<SelectListItem>;

  statusList: Array<SelectListItem>;
  /**
  * 构造函数，在此处配置依赖注入
  */
  constructor(
    injector: Injector,
    private _stockService: StockServiceProxy

  ) {
    super(injector);
  }

  ngOnInit(): void {
    this.init();
  }


  /**
  * 初始化方法
  */
  init(): void {
    console.log('import')
    this._stockService.getForEdit(undefined).subscribe(result => {
      this.categoryList = result.categoryList; //获取分类
    });
  }

  /**
  * 保存方法,提交form表单
  */
  submitForm(): void {
    ;
    this._stockService.toExcelData(this.inputdata, Number(this.entity.categoryId)).subscribe(result => {
          this.notify.success(this.l('SavedSuccessfully'));
          this.success(true);
      });
    

    this.saving = true;

    // this._stockService.createOrUpdate(input)
    //   .pipe(finalize(() => (this.saving = false)))
    //   .subscribe(() => {
    //     this.notify.success(this.l('SavedSuccessfully'));
    //     this.success(true);
    //   });
  }

  

  set_type() {
    console.log(this.entity.type)
  }

   /**导入**/
  //导入方法
  // 导入
  daoru(evt: any) {
    /* wire up file reader */
    const target: DataTransfer = <DataTransfer>(evt.target);

    if (target.files.length !== 1) throw new Error('Cannot use multiple files');
    const reader: FileReader = new FileReader();
    reader.onload = (e: any) => {
      /* read workbook */
      const bstr: string = e.target.result;
      const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });

      /* grab first sheet */
      const wsname: string = wb.SheetNames[0];
      const ws: XLSX.WorkSheet = wb.Sheets[wsname];

      /* save data */
      this.inputdata = (XLSX.utils.sheet_to_json(ws, { header: 1 }));
      this.inputdata.shift();
      this.inputdata.shift();
      console.log(this.inputdata)
      //清空file数据
      evt.target.value = "" // 清空

      // 数据验证
      var regu = "^[ ]+$";
      var re = new RegExp(regu);
      for (let i = 0; i < this.inputdata.length; i++) {
        if (re.test(this.inputdata[i].toString())) {
          this.inputdata.splice(i, 1)
          continue
        }
        for (let j = 0; j < this.inputdata[i].length; j++) {
          let v=this.inputdata[i][j]
          switch (j) {
            case 0:
              if (!(v == '单选题' || v == '多选题')) {
              this.notify.warn('第'+(i+3)+'行'+(j+1)+'列数据格式错错误，题目类型仅能为“单选题”、“多选题”');
              return 
              }
              break;
            case 2:
              if (!isNumber(v) || v<0) {
              this.notify.warn('第'+(i+3)+'行'+(j+1)+'列数据格式错错误，分数必须为非负数');
              return 
              }
              break;
            default:
              break;
          }
          this.inputdata[i][j]=this.inputdata[i][j]?this.inputdata[i][j]:''
        }
      }
      // console.log(this.inputdata)
      this.isSubmit=true
    };
    reader.readAsBinaryString(target.files[0]);

  }

}
